package handlers

import (
	"encoding/json"
	"github.com/julienschmidt/httprouter"
	"io"
	"io/ioutil"
	"log"
	"net/http"
	"video/api/databases"
	"video/api/models"
	"video/api/response"
	"video/api/session"
)

func CreateUser(w http.ResponseWriter, r *http.Request, _ httprouter.Params) {
	res, _ := ioutil.ReadAll(r.Body)
	log.Println(string(res))
	ubody := models.UserCredential{}
	if err := json.Unmarshal(res, &ubody); err != nil {
		response.SendErrorResponse(w, response.ErrorRequestBodyParseFailed)
		return
	}

	if err := databases.AddUserCredential(ubody.Username, ubody.Pwd); err != nil {
		response.SendErrorResponse(w, response.ErrorRequestBodyParseFailed)
		return
	}

	sessionId := session.GenerateNewSessionId(ubody.Username)
	sessionModel := models.SessionData{SessionId: sessionId}
	result := models.ResponseResult{Error: "创建成功", ErrorCode: "200", Data: sessionModel}

	if results, err := json.Marshal(result); err != nil {
		response.SendErrorResponse(w, response.ErrorRequestBodyParseFailed)
		return
	} else {
		response.SendNormalResponse(w, string(results), http.StatusOK)
	}

}

func Login(w http.ResponseWriter, r *http.Request, p httprouter.Params) {
	uname := p.ByName("user_name")
	io.WriteString(w, uname)
}
